<template>
  <base-list-page
    :columns="columns"
    :data-source="dataList"
    :loading="loading"
    :pagination="pagination"
    :search-items="searchItems"
    :actions="actions"
    :row-key="'id'"
    @search="handleSearch"
    :query-params="queryParams"
    @reset="handleReset"
    @change="handleTableChange"
    @action="handleAction"
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'roles'">
        <a-space>
          <a-tag v-for="role in record.roles" :key="role.id" color="blue">
            {{ role.name }}
          </a-tag>
        </a-space>
      </template>
      <template v-if="column.key === 'action'">
        <a-space>
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a @click="handleRoleAssign(record)">分配角色</a>
          <a-divider type="vertical" />
          <a-popconfirm title="确定要删除此用户吗？" ok-text="确定" cancel-text="取消" @confirm="handleDelete(record)">
            <a class="danger-text">删除</a>
          </a-popconfirm>
        </a-space>
      </template>
    </template>
    <template #extraContent>
      <!-- 用户表单弹窗 -->
      <user-form-modal
        v-if="modalVisible"
        ref="userFormModalRef"
        v-model:visible="modalVisible"
        :formState="formState"
        :modalTitle="modalTitle"
        @submit="submitForm"
        @cancel="resetForm"
      />

      <!-- 角色分配弹窗 -->
      <role-assign-modal
        v-model:visible="roleModalVisible"
        :loading="false"
        :submitLoading="roleSubmitLoading"
        :roleList="roleList"
        :userRoles="selectedRoles"
        :userId="currentUserId"
        @submit="handleRoleSubmit"
        @cancel="roleModalVisible = false"
      />
    </template>
  </base-list-page>
</template>

<script setup>
import { getUserList, getRoleList, addUser, updateUser, deleteUser, assignUserRoles } from "@/request/api";
import { UserAddOutlined } from "@ant-design/icons-vue";
import { useTableCrud } from "@/hooks/table/useTableCrud";
import UserFormModal from "./modal/UserFormModal.vue";
import RoleAssignModal from "./modal/RoleAssignModal.vue";
import { message } from "ant-design-vue";
import { onMounted } from "vue";
const userFormModalRef = ref(null)
// 使用通用CRUD hook
const {
  // 状态
  dataList,
  loading,
  pagination,
  formState,
  selectedRowKeys,
  selectedRows,
  searchParams,
  modalVisible,
  submitLoading,
  modalTitle,
  queryParams,

  // 方法
  loadData,
  handleAdd,
  handleEdit,
  handleDelete,
  handleBatchDelete,
  refreshData,
  submitForm,
  resetForm,
  handleSearch,
  handleReset,
  handleTableChange,
  clearSelection
} = useTableCrud({
  api: {
    list: getUserList,
    add: addUser,
    delete: deleteUser,
    update:updateUser
  },
  queryParams: {
    query: 'admin',
  }
});

// 角色相关状态
const roleList = ref([]);
const roleModalVisible = ref(false);
const roleSubmitLoading = ref(false);
const selectedRoles = ref([]);
const currentUserId = ref(null);
// 加载角色列表
const loadRoleList = async () => {
  try {
    const res = await getRoleList();
    if (res.code === 200) {
      roleList.value = res.data.list;
    } else {
      message.error(res.message || "获取角色列表失败");
    }
  } catch (error) {
    console.error("加载角色列表出错:", error);
    message.error("加载角色列表失败");
  }
};
// 打开角色分配模态框
const handleRoleAssign = async (record) => {
  await loadRoleList();
  currentUserId.value = record.id;
  selectedRoles.value = record.roles ? record.roles.map((role) => role.id) : [];
  roleModalVisible.value = true;
};
// 提交角色分配
const handleRoleSubmit = async (data) => {
  roleSubmitLoading.value = true;
  try {
    const res = await assignUserRoles(data);

    if (res.code === 200) {
      message.success("角色分配成功");
      roleModalVisible.value = false;
      await loadData();
    } else {
      message.error(res.message || "角色分配失败");
    }
  } catch (error) {
    console.error("分配角色出错:", error);
    message.error("角色分配失败");
  } finally {
    roleSubmitLoading.value = false;
  }
};
// 表格列定义
const columns = [
  { title: "用户名", dataIndex: "username", key: "username" },
  { title: "姓名", dataIndex: "name", key: "name" },
  { title: "邮箱", dataIndex: "email", key: "email" },
  { title: "角色", dataIndex: "roles", key: "roles" },
  { title: "创建时间", dataIndex: "created_at", key: "created_at" },
  { title: "操作", key: "action", fixed: "right", width: 250 }
];
// 搜索配置
const searchItems = [
  {
    name: "query",
    label: "关键词",
    component: "a-input",
    props: {
      placeholder: "搜索用户名/姓名/邮箱",
      allowClear: true
    }
  },
  {
    name: "role",
    label: "角色类型",
    component: "a-select",
    props: {
      placeholder: "请选择角色类型",
      allowClear: true,
      options: [
        { label: "管理员", value: "admin" },
        { label: "普通用户", value: "user" }
      ]
    }
  }
];
// 操作按钮配置
const actions = [
  {
    label: "新增用户",
    props: {
      type: "primary"
    },
    icon: UserAddOutlined,
    handler: handleAdd,
    key: "add",
    permission: "system:user:add"
  }
];
// 处理操作按钮点击
const handleAction = (action) => {
  if (action.key === "add") {
    handleAdd();
  }
};
</script>
